#!/bin/bash
[ $# -eq 0 ] && { echo "Usage: $0 ORIG_LANG DEST_LANG WORDSFILE"; exit 1; }

LANG=C
ORIG_DIR=Test-$1
DEST_DIR=Test-$2
ANNOTX_DIR=annotations/Annotx-$2

cat $3 | while read WORD
do
	mkdir -p $ANNOTX_DIR

	echo processing $WORD
	# get senses
	cat $ORIG_DIR/$WORD/LEXELT-test.xml | grep '<answer' \
	| sed 's/<.*instance="\([0-9]*\)".*senseid="\([0-9]*\).*/\1 \2/' > $ANNOTX_DIR/$WORD-senses.txt
	
	# get the sentences
	cat $ORIG_DIR/$WORD/LEXELT-test.xml \
	| grep -Ev '<.*instance.*>|<.*context.*>|<.*lexelt.*>|<.*corpus.*>' > $ANNOTX_DIR/$WORD-sentences.txt
		#| cut -c 1-100 \

	cd $ANNOTX_DIR

		# merge line-by-line
		paste $WORD-senses.txt $WORD-sentences.txt | sort | uniq -u > $WORD-annotations.txt
		rm $WORD-senses.txt $WORD-sentences.txt
		
		echo -e '<corpus lang="english">\n<lexelt item="LEXELT">' > $WORD-test.xml

		# FIXME: There are some dirty things here
		cat $WORD-annotations.txt | while read id senseid LINE
		do		
			cat ../../$DEST_DIR/$WORD/$WORD-corpus.xml \
			| grep -A 2 -B 3 "^`echo $LINE | sed 's/^-//'`" | grep -Ev '\-\-' \
			| grep -B 5 -m 1 '</instance>' \
			| sed -e "s/\(\<instance id=\"\)[0-9]*\(\".*\)/\1$id\2/" \
			| sed -e "s/\(.*instance=\"\)[0-9]*\(\".*senseid=\"\)NOTAG\(\".*\)/\1$id\2$senseid\3/" >> $WORD-test.xml
		done

		echo -e '</lexelt>\n</corpus>' >> $WORD-test.xml
		cp $WORD-test.xml ../../$DEST_DIR/$WORD/LEXELT-test.xml
	cd ../..
done